<template>
  <div class="fixture_maintain_detail form_detail_page" v-loading="isLoading">
    <one-title :title="$route.query.id ? '工装夹具台账详情' : '工装夹具台账新增'" @refreshData="refresh"></one-title>
    <el-form ref="listForm" class="fixed_top_56" :model="detailData" :rules="rules" v-if="!isEmpty&&!isLoading">
      <two-title title="基本信息"></two-title>
      <div class="from_panel">
        <div class="form_col form_col_left">
          <el-form-item class="form_item" label="资源编号:" prop="number">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入资源编号"
                        v-model.trim="detailData.number"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="资源名称:" prop="name">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入资源名称"
                        v-model.trim="detailData.name"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="数量:" prop="quantity">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入数量"
                        v-model.trim="detailData.quantity"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="单位:" prop="unit">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入单位"
                        v-model.trim="detailData.unit"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="资源类型:" prop="typeId">
            <div class="input_wapper">
              <el-select size="small" v-model.trim="detailData.typeId" filterable placeholder="请选择资源类型"
                         @change="getLabel">
                <el-option
                  v-for="item in resourceType"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
            <div class="clear_panel"></div>
          </el-form-item>
        </div>
        <div class="form_col form_col_right">
          <el-form-item class="form_item" label="所属零件名称:" prop="partName">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入所属零件名称"
                        v-model.trim="detailData.partName"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="所属零件图号:" prop="partDrawingNumber">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入所属零件图号"
                        v-model.trim="detailData.partDrawingNumber"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="工装大类:" prop="resourceLargeClass">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入工装大类"
                        v-model.trim="detailData.resourceLargeClass"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="工装小类:" prop="resourceSmallClass">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入工装小类"
                        v-model.trim="detailData.resourceSmallClass"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
        </div>
        <div class="clear_panel"></div>
      </div>
      <two-title title="制造信息"></two-title>
      <div class="from_panel">
        <div class="form_col form_col_left">
          <el-form-item class="form_item" label="制造厂家:" prop="manufacturer">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入制造厂家"
                        v-model.trim="detailData.manufacturer"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="制造日期:" prop="purchaseDate">
            <div class="input_wapper">
              <el-date-picker
                v-model="detailData.purchaseDate"
                type="date"
                size="small"
                :clearable="false"
                placeholder="请选择制造日期"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
              <i class="date_icon"></i>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="资源寿命:" prop="lifeTime">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入资源寿命"
                        v-model.trim="detailData.lifeTime"
                        clearable>
                <template slot="append">年</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="预警寿命:" prop="warningLifeTime">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入预警寿命"
                        v-model.trim="detailData.warningLifeTime"
                        clearable>
                <template slot="append">年</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label=" ">
            <label></label>
            <div class="input_wapper mes_btn">
              <el-button type="primary" @click="save">保存</el-button>
              <el-button @click="cancel">取消</el-button>
            </div>
          </el-form-item>
        </div>
        <div class="form_col form_col_right">
          <el-form-item class="form_item" label="厂商批次:" prop="manufacturerBatchNumber">
            <div class="input_wapper">
              <el-input size="small"
                        placeholder="请输入厂商批次"
                        v-model.trim="detailData.manufacturerBatchNumber"
                        clearable>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="资源主管:" prop="resourceManagerId">
            <div class="input_wapper">
              <el-select placeholder="请选择资源主管" size="small" v-model.trim="detailData.resourceManagerId"
                         @change="getName">
                <el-option
                  v-for="item in staffList"
                  :key="item.ID"
                  :label="item.NAME"
                  :value="item.ID">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item class="form_item" label="备注:" prop="remarks">
            <div class="input_wapper text_area">
              <el-input size="small" type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        placeholder="请输入内容"
                        v-model="detailData.remarks"
                        maxlength="255"></el-input>
              <span class="text_length">{{detailData.remarks ? detailData.remarks.length : 0}}/255</span>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <empty-page v-if="isEmpty&&!isLoading"></empty-page>
  </div>
</template>

<script>
import TwoTitle from '@/components/TwoTitle'
import EmptyPage from '@/components/EmptyPage'

export default {
  name: 'FixtureManageDetail',
  data() {
    return {
      resourceManagerName: '',
      resourceTypeLabel: '',
      // 是否为空数据
      isEmpty: false,
      //  加载中
      isLoading: true,
      // 开始监听数据
      startWatch: false,
      // 表单格式验证
      rules: {
        unit: [
          {required: true, message: '请输入单位', trigger: 'blur'},
          {max: 20, message: '单位长度不能超过10字符', trigger: 'blur'}
        ],
        quantity: [
          {required: true, validator: this.isPosInteger, message: '数量必须是正整数', trigger: 'blur'}
        ],
        typeId: [
          {required: true, message: '请选择资源类型', trigger: 'blur'}
        ],
        number: [
          {required: true, message: '请输入资源编号', trigger: 'blur'},
          {max: 20, message: '资源编号长度不能超过20字符', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入资源名称', trigger: 'blur'},
          {max: 100, message: '资源名称长度不能超过100字符', trigger: 'blur'}
        ],
        lifeTime: [
          {validator: this.isPosInteger, message: '资源寿命必须是正整数', trigger: 'blur'}
        ],
        warningLifeTime: [
          {validator: this.isPosInteger, message: '预警寿命必须是正整数', trigger: 'blur'}
        ],
        manufacturer: [
          {max: 100, message: '制造厂家长度不能超过100字符', trigger: 'blur'}
        ],
        location: [
          {max: 100, message: '所在位置长度不能超过100字符', trigger: 'blur'}
        ],
        remarks: [
          {max: 255, message: '备注长度不能超过255字符', trigger: 'blur'}
        ]
      }
    }
  },
  components: {
    TwoTitle,
    EmptyPage
  },
  watch: {
    detailData: {
      // 监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        }
      },
      deep: true
    }
  },
  computed: {
    // 详情数据
    detailData() {
      return this.$store.state.fixTureManage.detailData
    },
    // 人员列表
    staffList() {
      const list = this.$store.state.fixTureManage.staffList.list || []
      return list.map((item) => {
        return {
          ID: item.id,
          NAME: item.name
        }
      })
    },
    // 资源类型
    resourceType() {
      return this.$store.state.dict.resourceType.labels || []
    },
    // 获取树形数据
    treeList() {
      return this.$store.state.treeList
    },
    // 工装夹具"正常"状态ID(有状态id保存时参数为原有状态id,没有默认传递状态为"正常")
    fixTureStatusId() {
      if (this.detailData.resourceStatusId) {
        return this.detailData.resourceStatusId
      } else {
        let list = this.$store.state.dict.ResourceStatus.labels || []
        let item = list.find((item) => item.value === 'Normal')
        return item ? item.id : ''
      }
    },
  },
  mounted() {
    this.getStaff()
    this.init()
  },
  methods: {
    // 获取人员列表
    getStaff() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/staff/staff/list',
        data: {
          pageNo: 1,
          pageSize: 9999,
          query: {
            columns: ['name']
          },
          sort: { name: 'asc' }
        },
        module: 'fixTureManage',
        state: 'staffList'
      })
    },
    // 审计项需要特殊处理-修改时传递的资源主管名称
    getName(val) {
      const list = this.staffList.filter(v => v.ID === val)
      this.resourceManagerName = list[0].NAME
    },
    // 审计项需要特殊处理-修改时传递的资源类型名称
    getLabel(val) {
      const list = this.resourceType.filter(v => v.id === val)
      this.resourceTypeLabel = list[0].label
    },
    // 更新方法
    refresh() {
      this.init()
    },
    // 初始化方法
    init() {
      this.isLoading = true
      this.startWatch = false
      Promise.all([this.getDetail(), this.getTreeList()]).then(() => {
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
    },
    // 获取详情
    getDetail() {
      let id = this.$route.query.id
      let postData = {
        method: 'get',
        module: 'fixTureManage',
        state: 'detailData',
        url: 'a/manufactureresource/manufactureResource/get/' + id
      }
      if (!id) {
        postData.clean = true
      }
      return this.$store.dispatch('saveData', postData).then((res) => {
        this.startWatch = true
        if (id && !res) {
          this.isEmpty = true
        }
      }).catch(() => {
        this.isEmpty = true
      })
    },
    // 初始化树形结构数据
    getTreeList() {
      return this.$store.dispatch('getTreeList')
    },
    // 是否是正整数
    isPosInteger(rule, num, callback) {
      if (num) {
        if (!/^[0-9]*[1-9][0-9]*$/.test(num)) {
          callback(new Error(rule.message))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    // 保存
    save() {
      if (this.saveState === false) return
      this.detailData.resourceManagerName = this.resourceManagerName ? this.resourceManagerName : this.detailData.resourceManagerName
      this.detailData.resourceTypeLabel = this.resourceTypeLabel ? this.resourceTypeLabel : this.detailData.resourceTypeLabel
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.detailData.resourceStatusId = this.fixTureStatusId
          let postData = {
            method: 'post',
            url: 'a/manufactureresource/manufactureResource/saveuniquenumber',
            data: this.detailData,
            noCommit: true
          }
          let $route = this.$route
          this.$store.dispatch('saveData', postData).then(() => {
            this.saveSuccess($route)
          }).catch(() => {
            this.saveState = true
          }).finally(() => {
            this.isLoading = false
          })
        } else {
          return false
        }
      })
    },
    // 保存成功回调
    saveSuccess($route) {
      this.$message({
        message: '保存成功',
        type: 'success',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false)
          this.$store.dispatch('delCurrentViews', $route).then(() => {
            this.$router.push('/fixTureManage')
            this.$store.commit('SetRefresh', true) // 跳转到列表页刷新
          })
        }
      })
    },
    // 取消
    cancel() {
      let $route = this.$route
      this.backToList().then(() => {
        this.$store.dispatch('delCurrentViews', $route).then(() => {
          this.$router.push('/fixTureManage')
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
  .fixture_maintain_detail {
    .fixed_top_56 {
      padding-bottom: 10px;
    }
  }
</style>
